package com.css.fxfzaqbz.modules.supergraph.repository.impl;

import com.css.fxfzaqbz.modules.supergraph.repository.OrgDivisionRepository;
import com.css.fxfzaqbz.org.entity.DivisionEntity;
import com.css.fxfzaqbz.util.PlatformObjectUtils;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import java.util.List;

@Repository
public class OrgDivisionRepositoryImpl implements OrgDivisionRepository {

    @Resource
    JdbcTemplate jdbcTemplate;

    //根据1个任务地区查询行政区划code
    @Override
    public String getCodeByTaskDistrict(String taskDistrict){
        String code = "";
        if (!PlatformObjectUtils.isEmpty(taskDistrict) ){
            StringBuilder sql = new StringBuilder("SELECT * FROM org_division ");
            StringBuilder whereSql = new StringBuilder(" where is_valid='1'");
            if(taskDistrict.indexOf("-")!=-1){
                String[] districtArr = taskDistrict.split("-");
                if(districtArr.length==2){//市或直辖市的区
                    whereSql.append(" and division_name='" + districtArr[1] + "'");
                    whereSql.append(" and parent_id in (SELECT division_id FROM org_division ");
                    whereSql.append(" where is_valid='1' ");
                    whereSql.append(" and division_name='" + districtArr[0] + "')");

                }else if(districtArr.length==3){//区县
                    whereSql.append(" and division_name='" + districtArr[2] + "'");
                    whereSql.append(" and parent_id in (SELECT division_id FROM org_division ");
                    whereSql.append(" where is_valid='1' ");
                    whereSql.append(" and division_name='" + districtArr[1] + "'");
                    whereSql.append(" and parent_id in (SELECT division_id FROM org_division ");
                    whereSql.append(" where is_valid='1' ");
                    whereSql.append(" and division_name='" + districtArr[0] + "'))");
                }
            }else{
                //省
                whereSql.append(" and division_name='" + taskDistrict + "'");
            }
            sql.append(whereSql).toString();
            List<DivisionEntity> list = jdbcTemplate.query(sql.toString(), new BeanPropertyRowMapper<>(DivisionEntity.class));
            if(list!=null && list.size()==1){
                String divisionCode = list.get(0).getDivisionCode();
                if (!PlatformObjectUtils.isEmpty(divisionCode)){
                    code = divisionCode;
                }
            }
        }

        return code;
    }
}
